package com.xue.apitest.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xue.apitest.constant.ResultEntity;
import java.util.Map;

/**
 * @Author xue
 * @Date 2021/6/19 11:41
 */
public class JsonUtils {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 对象转json
     * @param obj   要转换的对象
     * @return      返回json字符串
     */
    public static String objToJson(Object obj){
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json转对象
     * @param json 要转换的json字符串
     * @return     返回指定对象
     */
    public static ResultEntity<?> jsonToObj(String json){
        try {
            return OBJECT_MAPPER.readValue(json, ResultEntity.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json转Map
     * @param json 要转换的json字符串
     * @return  返回Map对象
     */
    public static Map jsonToMap(String json){
        try {
            return OBJECT_MAPPER.readValue(json, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * map转json
     * @param map 需要转换的map
     * @return  返回json字符串
     */
    public static String mapToJson(Map<String,Object> map){
        try {
            return OBJECT_MAPPER.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
